﻿using System.IdentityModel.Tokens.Jwt;
using System.Text;
using blog.Model.Oo;
using Microsoft.IdentityModel.Tokens;

namespace blog.web.WebFunc;

public class AboutToken
{
    public static string GetToken(IHttpContextAccessor accessor)
    {
        var token =  accessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
                     ?? accessor.HttpContext.Request.Headers["token"].FirstOrDefault()
                     ?? accessor.HttpContext.Request.Query["Token"].FirstOrDefault()
                     ?? accessor.HttpContext.Request.Cookies["Token"];
        return token ?? string.Empty;
    }
    
    /// <summary>
    /// 验证用户token
    /// </summary>
    /// <param name="token"></param>
    /// <param name="_authOptions"></param>
    /// <returns>用户id</returns>
    public static int ValidateUserToken(string token, JwtOpt _authOptions)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            byte[]? key = Encoding.ASCII.GetBytes(_authOptions.SecurityKey);
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidIssuer = _authOptions.Issuer,
                ValidAudience = _authOptions.Audience,
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;
            var user = jwtToken.Claims.First(x => x.Type == "userid").Value;
            int uid = int.Parse(user);
            return uid;
        }
        catch
        {
            return 0;
        }
    }
}